<template>
  <div class="app-container">
    <el-drawer :title="title" :visible.sync="openDetail" size="85%" @close="cancel" :append-to-body="true">
      <template v-slot:title>
        <span class="titleDiv">{{ title }}</span>
      </template>
      <div style="padding: 0 20px">
        <div>
          <div style="display:flex;  align-items: flex-start;  justify-content: space-between;">
            <div style="width: 49%;">
              <div>
                <el-tag size="large" style="font-size: 20px;margin-right:10px;">原版本BOM用料清单</el-tag>
                <el-select v-model="oldversion" placeholder="请选择BOM版本" value-key="id" @change="(e)=>selectChange(e,'old')">
                  <el-option v-for="item in oldList" :key="'old' + item.id" :label="''+ item.version" :value="item"></el-option>
                </el-select>
              </div>

              <hr />
              <el-table v-loading="loading" :data="oldBomList" :row-class-name="tableRowClassName" style="max-height:400px;overflow-y: scroll;">
                <el-table-column label="序号" align="center" width="50px">
                  <template slot-scope="scope">
                    <span>{{scope.$index + 1}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="物料编号" align="center" width="110px" prop="itemCode"></el-table-column>
                <el-table-column label="物料名称" align="center" prop="itemName"></el-table-column>
                <el-table-column label="规格型号" align="center" prop="specification" />
                <el-table-column label="数量" align="center" prop="fmustQty" />
              </el-table>
            </div>
            <div style="width: 49%;">
              <div>
                <el-tag size="large" style="font-size: 20px;margin-right:10px;">新版本BOM用料清单</el-tag>
                <el-select v-model="newversion" placeholder="请选择BOM版本" value-key="id" @change="(e)=>selectChange(e,'new')">
                  <el-option v-for="item in newList" :key="'new' + item.id" :label="''+item.version" :value="item"></el-option>
                </el-select>
              </div>
              <hr />
              <el-table v-loading="loading" :data="newBomList" :row-class-name="tableRowClassName" style="max-height:400px;overflow-y: scroll;">
                <el-table-column label="序号" align="center" width="50px">
                  <template slot-scope="scope">
                    <span>{{scope.$index + 1}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="物料编号" align="center" width="110px" prop="itemCode"></el-table-column>
                <el-table-column label="物料名称" align="center" prop="itemName"></el-table-column>
                <el-table-column label="规格型号" align="center" prop="specification" />
                <el-table-column label="数量" align="center" prop="fmustQty" />
              </el-table>
            </div>
          </div>
          <el-tabs type="border-card" style="margin-top:10px;" @tab-click="tabchange">
            <!-- <el-tab-pane label="虚拟入库">
              <el-table
                v-loading="loading"
                :data="virtualList"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" align="center" width="50px">
                  <template slot-scope="scope">
                    <span>{{scope.$index + 1}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="SN" align="center" prop="snCode"></el-table-column>
              </el-table>
            </el-tab-pane> -->
            <el-tab-pane label="清单对比结果">
              <el-table v-loading="loading" :data="partBomList">
                <el-table-column label="序号" align="center" width="50px">
                  <template slot-scope="scope">
                    <span>{{scope.$index + 1}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="物料编号" align="center" width="110px" prop="itemCode"></el-table-column>
                <el-table-column label="物料名称" align="center" prop="itemName"></el-table-column>
                <el-table-column label="规格型号" align="center" prop="specification" />
                <el-table-column label="类型" align="center" prop="compareType">
                  <template slot-scope="scope">
                    <span>{{scope.row.compareType==1 ? "退料":"增料"}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="数量" align="center" prop="comparedQuantity" />
              </el-table>
            </el-tab-pane>
            <!--
            <el-tab-pane label="全部退料">
              <el-table v-loading="loading" :data="allBomList">
                <el-table-column label="序号" align="center" width="50px">
                  <template slot-scope="scope">
                    <span>{{scope.$index + 1}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="物料编号" align="center" width="110px" prop="materialCode"></el-table-column>
                <el-table-column label="物料名称" align="center" prop="materialName"></el-table-column>
                <el-table-column label="规格型号" align="center" prop="materialSpec" />
              </el-table>
            </el-tab-pane>
            -->
          </el-tabs>
          <div slot="footer" class="dialog-footer" style="margin-top:14px;text-align:right">
            <el-button type="danger" @click="handleQuantity">确定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

  <script>
import {
  getVirtualStokcinInfos,
  getMaterialInfoList,
  getMaterialInfoList2,
  getVersions,
  getMaterialListOfOldSubNew,
  getMaterialInfoListOfCurrVersion,
  rejectWholeWorkOrder,
  changeBomVersion,
  getMaterialListOfOldSubNew2
} from "@/api/mes/pro/workorder";
export default {
  data() {
    return {
      openDetail: false,
      title: "物料清单变更",
      // 表单参数
      form: {},
      requisitionForm: {},
      loading: false,
      oldBomList: [],
      newBomList: [],
      loading1: false,
      newList: [],
      oldList: [],
      newversion: null,
      oldversion: null,
      virtualList: [],
      partBomList: [],
      isSubmitting: false, // 防重复提交标志

    };
  },
  methods: {
    //初始化函数
    init(row) {
      console.log(row, "子组件的row");
      this.form = row;
      //调接口需要的id
      this.workorderId = row.workorderId;
      this.openDetail = true;
      this.getList();
      // this.getVirtual();  //2024年 6月7日 陈伟说的把虚拟入库隐藏
      // this.getAllMaterList();
    },
    tableRowClassName({ row, rowIndex }) {
      console.log(row)
      if (row.flag) {
        return 'warning-row';
      }
    },
    // 查询bom版本
    getList() {
      // this.loading = true;
      let query = {
        workorderId: this.form.workorderId
      };
      console.log(query, "=====");
      getVersions(query).then(res => {
        console.log(res, "==res==");
        this.oldList = res.data.old || [];
        this.newList = res.data.new || [];
        let oldParam = null
        let newParam = null
        if (this.oldList.length) {
          let maxVersion = 0
          let maxIndex = 0
          this.oldList.forEach((item, index) => {
            if (item.version > maxVersion) {
              maxVersion = item.version
              maxIndex = index
            }
          })
          this.oldversion = this.oldList[maxIndex]
          oldParam = {
            fbomId: this.oldList[maxIndex].bomId,
            version: this.oldList[maxIndex].version,
            workorderId: this.form.workorderId
          }
        }
        if (this.newList.length) {
          let maxVersion = 0
          let maxIndex = 0
          this.newList.forEach((item, index) => {
            if (item.version > maxVersion) {
              maxVersion = item.version
              maxIndex = index
            }
          })
          this.newversion = this.newList[maxIndex]
          newParam = {
            fbomId: this.newList[maxIndex].bomId,
            version: this.newList[maxIndex].version,
            workorderId: this.form.workorderId
          }
        }

        Promise.all([oldParam ? getMaterialInfoList2(oldParam) : [], newParam ? getMaterialInfoList2(newParam) : []]).then(result => {
          this.oldBomList = result[0].bomItems || [];
          this.newBomList = result[1].bomItems || [];
          if ((this.oldversion && this.oldversion.id) && (this.newversion && this.newversion.id)) {
            this.getMaterList();
          }
        })
        this.title = "物料清单变更";
        // this.$set(this.form, "routeName", routeName);
      });
    },
    // 虚拟入库列表
    getVirtual() {
      let query = {
        workOrderCode: this.form.workorderCode
      };
      getVirtualStokcinInfos(query).then(res => {
        this.virtualList = res.data;
      });
    },
    selectChange(e, type) {
      console.log(e, type, "======type======");
      this.getBomList(e, type);
    },
    // bom列表
    getBomList(e, type) {
      let param = {
        fbomId: e.bomId,
        version: e.version,
        workorderId: this.form.workorderId
      };
      getMaterialInfoList2(param).then(res => {
        if (type === 'old') {
          this.oldBomList = res.bomItems || [];
        } else {
          this.newBomList = res.bomItems || [];
        }
        console.log(111, this.oldversion)
        console.log(222, this.newversion)
        if ((this.oldversion && this.oldversion.id) && (this.newversion && this.newversion.id)) {
          this.getMaterList();
        }
      });
    },
    tabchange(e) {
      let name = e.label;
      if (name == "部分退料") {
      } else if (name == "全部退料") {
      }
      console.log(name, "=====e=======");
    },
    // 清单对比结果
    getMaterList() {
      let param = {
        oldBomItems: this.oldBomList,
        newBomItems: this.newBomList
      }
      let that = this
      getMaterialListOfOldSubNew2(param).then(res => {
        this.partBomList = res.data || [];
        this.oldBomList.forEach((item, index) => {
          let flag = false
          this.partBomList.forEach(item2 => {
            if (item.itemCode === item2.itemCode) {
              flag = true
            }
          })
          if (flag) {
            item.flag = true
          }
          else {
            item.flag = false
          }
          that.$set(that.oldBomList, index, item)
        })
        this.newBomList.forEach((item, index) => {
          let flag = false
          this.partBomList.forEach(item2 => {
            if (item.itemCode === item2.itemCode) {
              flag = true
            }
          })
          if (flag) {
            item.flag = true
          }
          else {
            item.flag = false
          }
          that.$set(that.newBomList, index, item)
        })
        console.log('newBomList', this.newBomList)
      })
    },

    // getAllMaterList() {
    //   let param = {
    //     workOrderCode: this.form.workorderCode
    //   };
    //   getMaterialInfoListOfCurrVersion(param).then(res => {

    //   });
    // },
    // 取消按钮
    cancel() {
      this.openDetail = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.requisitionForm = {
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        status: 0,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        orderType: null,
        fPlanStartDate: null,
        fPlanFinishDate: null
      };
      this.autoGenFlag = false;
      this.newList = [];
      this.oldList = [];
      this.virtualList = [];
      this.oldversion = null;
      this.newversion = null;
      this.partBomList = [];
      this.virtualList = [];
      this.oldBomList = [];
      this.newBomList = [];

      this.resetForm("requisitionForm");
    },
    // 确定
    handleQuantity() {
      if (this.oldversion.version == null || this.oldversion.version === '' ||
        this.newversion.version == null || this.newversion.version === '') {
        this.$modal.msgError("请选择需要变更的版本！");
        return;
      }
      if (this.isSubmitting) {
        this.$modal.msgWarning("请求正在处理中，请勿重复提交");
        return;
      } // 如果正在提交中，直接返回
      this.isSubmitting = true;
      let param = {
        workorderId: this.form.workorderId,
        bomList: this.partBomList,
        oldVersion: this.oldversion.version,
        newVersion: this.newversion.version
      };

      changeBomVersion(param)
        .then(res => {
          this.$modal.msgSuccess(res.msg);
          this.openDetail = false;
          this.reset();
          this.$emit("getList");
        })
        .finally(() => {
          this.isSubmitting = false; // 无论成功失败都恢复提交状态
        });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.snId);
      this.queryParams.proWorkorderSnIdList = selection.map(item => item.snId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    }
  }
};
</script>
    <style rel="stylesheet/scss" lang="scss" scoped>
.app-container ::v-deep {
  .el-drawer__header {
    padding-top: 10px !important;
    padding-bottom: 5px !important;
    margin-bottom: 10px !important;
  }
  .dialog-footer {
    padding-top: 10px;
    text-align: right;
  }
  .titleDiv {
    font-weight: 700 !important;
    font-size: 20px;
  }
}
</style>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
